<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户反馈管理</span>
      </div>

      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="form-inline">
          <el-form-item label="关键词">
            <el-input
              v-model="queryParams.search"
              placeholder="内容/联系方式"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="未处理" :value="0" />
              <el-option label="已处理" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="提交日期">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading"
              >查询</el-button
            >
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="feedbackList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="用户信息" width="180">
          <template #default="{ row }">
            <template v-if="row.user">
              <div>{{ row.user.nick_name || "匿名用户" }}</div>
              <div v-if="row.user.mobile" class="text-muted">
                {{
                  userStore.isTest
                    ? maskMobile(row.user.mobile)
                    : row.user.mobile
                }}
              </div>
            </template>
            <span v-else>匿名用户</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="contact"
          label="联系方式"
          width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ userStore.isTest ? maskContact(row.contact) : row.contact }}
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="反馈内容"
          min-width="250"
          show-overflow-tooltip
        />
        <el-table-column
          prop="create_time"
          label="提交时间"
          width="170"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'warning' : 'success'">
              {{ row.status === 0 ? "未处理" : "已处理" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <!-- <el-button size="mini" type="primary" @click="handleViewDetail(row)"
              >查看</el-button
            > -->
            <!-- <el-button
              size="mini"
              type="success"
              v-if="row.status === 0"
              @click="handleReply(row)"
              :disabled="userStore.isTest"
              >回复</el-button
            > -->
            <el-button size="mini" type="danger" @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.per_page"
          :current-page="queryParams.page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog title="回复反馈" v-model="replyDialogVisible" width="500px">
      <el-form
        :model="replyForm"
        :rules="replyRules"
        ref="replyFormRef"
        label-width="80px"
      >
        <el-form-item label="反馈内容">
          <div class="feedback-content">{{ currentFeedback.content }}</div>
        </el-form-item>
        <el-form-item label="回复内容" prop="reply">
          <el-input
            type="textarea"
            :rows="4"
            v-model="replyForm.reply"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitReply"
            :loading="submitLoading"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, inject } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/store/user";
import request from "@/utils/request";
const router = useRouter();
const userStore = useUserStore();
const replyFormRef = ref(null);
const loading = ref(false);
const submitLoading = ref(false);
const feedbackList = ref([]);
const total = ref(0);
const dateRange = ref([]);
const replyDialogVisible = ref(false);
const currentFeedback = ref({});

// 查询参数
const queryParams = reactive({
  page: 1,
  per_page: 10,
  search: "",
  status: "",
  start_date: "",
  end_date: "",
  user_id: "",
});

// 回复表单
const replyForm = reactive({
  reply: "",
});

// 表单验证规则
const replyRules = {
  reply: [{ required: true, message: "请输入回复内容", trigger: "blur" }],
};

// 获取反馈列表
const getFeedbacks = async () => {
  loading.value = true;
  try {
    const response = await request.get("/admin/feedbacks", {
      params: queryParams,
    });
    console.log("获取反馈列表响应", response);

    if (response.code === 0) {
      feedbackList.value = response.data.items;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.message || "获取反馈列表失败");
    }
  } catch (error) {
    console.error("获取反馈列表失败", error);
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  queryParams.page = 1;
  getFeedbacks();
};

// 重置查询
const resetQuery = () => {
  queryParams.search = "";
  queryParams.status = "";
  queryParams.start_date = "";
  queryParams.end_date = "";
  queryParams.user_id = "";
  dateRange.value = [];
  handleSearch();
};

// 日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    queryParams.start_date = val[0];
    queryParams.end_date = val[1];
  } else {
    queryParams.start_date = "";
    queryParams.end_date = "";
  }
};

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.per_page = val;
  getFeedbacks();
};

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.page = val;
  getFeedbacks();
};

// 查看详情
const handleViewDetail = (row) => {
  router.push(`/feedback/detail/${row.id}`);
};

// 打开回复对话框
const handleReply = (row) => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能回复反馈");
    return;
  }

  currentFeedback.value = row;
  replyForm.reply = "";
  replyDialogVisible.value = true;

  nextTick(() => {
    if (replyFormRef.value) {
      replyFormRef.value.resetFields();
    }
  });
};

// 提交回复
const submitReply = async () => {
  if (!replyFormRef.value) return;

  try {
    const valid = await replyFormRef.value.validate();
    if (!valid) return;

    submitLoading.value = true;
    const response = await request.post(
      `/admin/feedbacks/reply/${currentFeedback.value.id}`,
      {
        reply: replyForm.reply,
      }
    );

    if (response.data.code === 0) {
      ElMessage.success("回复成功");
      replyDialogVisible.value = false;
      getFeedbacks();
    } else {
      ElMessage.error(response.data.message || "回复失败");
    }
  } catch (error) {
    console.error("回复失败", error);
    ElMessage.error("回复失败");
  } finally {
    submitLoading.value = false;
  }
};

// 删除反馈
const handleDelete = (row) => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能删除反馈");
    return;
  }

  ElMessageBox.confirm("确定要删除这条反馈吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await request.post(
          `/admin/feedbacks/delete/${row.id}`
        );
        if (response.code === 0) {
          ElMessage.success("删除成功");
          getFeedbacks();
        } else {
          ElMessage.error(response.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 手机号脱敏处理
const maskMobile = (mobile) => {
  if (!mobile) return "";
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};

// 联系方式脱敏处理
const maskContact = (contact) => {
  if (!contact) return "";
  // 处理邮箱
  if (contact.includes("@")) {
    const parts = contact.split("@");
    const name = parts[0];
    let maskedName = name;
    if (name.length > 2) {
      maskedName =
        name.substring(0, 1) + "***" + name.substring(name.length - 1);
    }
    return maskedName + "@" + parts[1];
  }
  // 处理手机号
  else if (/^\d{11}$/.test(contact)) {
    return contact.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
  }
  // 其他联系方式
  return (
    contact.substring(0, 1) + "***" + contact.substring(contact.length - 1)
  );
};

// 页面加载时获取数据
onMounted(() => {
  getFeedbacks();
});
</script>

<style scoped>
.filter-container {
  padding-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.feedback-content {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  max-height: 100px;
  overflow-y: auto;
}

.text-muted {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
</style>
